package com.boby.homecamera.net

import android.util.Log
import com.boby.homecamera.constant.Constant
import com.boby.homecamera.db.CameraDeviceTable
import com.boby.homecamera.db.VideoEventTable
import com.boby.homecamera.db.VideoTable.Video
import com.boby.homecamera.net.data.ApiResult
import com.boby.homecamera.webserver.model.UserInfo
import com.boby.lib_common.network.Net
import com.boby.lib_common.network.NetRequest
import com.boby.lib_common.util.MD5
import java.net.URLEncoder


internal object Api {
    private var baseUrl :String? = null
    fun setUrl(url:String){
        baseUrl = url
    }

    fun getRealUrl(url: String?,port:Int):String{
        if(url.isNullOrBlank()){
            return ""
        }
        var newUrl :String
        if(url.startsWith("http")){
            newUrl = url
        }else{
            newUrl ="http://$url"
        }
//        return "$newUrl:${Constant.HTTP_SERVER_PORT}"
        return "$newUrl:${port}"
    }


    fun getRtspUrl(url: String?,port: Int):String{
        if(url.isNullOrBlank()){
            return ""
        }
        var newUrl :String
        newUrl = url.replace("http://","").replace("https://","")
//        return "rtsp://$newUrl:${Constant.RTSP_PORT}"
        return "rtsp://$newUrl:${port}"
    }
    fun getIP(url: String?):String{
        if(url.isNullOrBlank()){
            return ""
        }
        val newUrl = url.replace("http://","").replace("https://","").replace("ws://","")
//        return "ws://$newUrl:${Constant.WEBSOCKET_PORT}"
        return newUrl
    }

    fun login(url: String,username:String,password:String, callBack: Net.CallBack<UserInfo>) {
        val req = "username=${URLEncoder.encode(username, "UTF-8")}&password=${URLEncoder.encode(password, "UTF-8")}"
        postAsync("$url/user/login", req, callBack)
    }

//    fun getUserInfo(callBack: Net.CallBack<UserInfo>) {
//        getAsync("$baseUrl/apis/user/info",null, callBack)
//    }
    fun getVideoList(url: String?,token: String?,startTime:Long,endTime: Long,callBack: Net.CallBack<List<Video>>) {
        val map = HashMap<String, Any>()
        map["startTime"] = startTime
        map["endTime"] = endTime
        getAsync("$url/video/videolist",token,map, callBack)
    }
    fun getVideoEventList(url: String?,token: String?,videoEvents:String?,startTime:Long,endTime: Long,isASC:Boolean,callBack: Net.CallBack<List<VideoEventTable.VideoEvent>>) {
        val map = HashMap<String, Any?>()
        map["startTime"] = startTime
        map["endTime"] = endTime
        map["videoEventTypes"] = videoEvents
        map["isASC"] = isASC
        getAsync("$url/video/video_event_list",token,map, callBack)
    }
    fun getVideoStartFileDate(url: String?,token: String?,callBack: Net.CallBack<Long>) {
        val map = HashMap<String, Any?>()
        getAsync("$url/video/video_Start_file_date",token,map, callBack)
    }



    inline  fun <reified T> postAsync(url:String,req:Any?,callBack: Net.CallBack<T>?){
//        val reqHeaders:HashMap<String,String> = HashMap()
//        reqHeaders["Content-Type"] = "application/json;charset=utf-8"
//        if(!InitManager.instance.token.isNullOrBlank()){
//            if(!InitManager.instance.token.isNullOrBlank()){
//                if(Constant.MODE_TOKEN_TYPE == 1){
//                    reqHeaders["Authorization"] = "Bearer ${InitManager.instance.token!!}"
//                }else{
//                    reqHeaders["Authorization"] = InitManager.instance.token!!
//                }
//            }
//        }

        NetRequest.postAsync(url,null, req,object :Net.CallBack<ApiResult<T?>>{
            override fun onSuccess(result: ApiResult<T?>?) {
                if(result?.isResultSuccess() == true){
                    callBack?.onSuccess(result.data)
                }else{
                    if(result?.code == Constant.ErrorCode.ERROR_CODE_TOKEN){
                        callBack?.onError(Constant.ErrorCode.ERROR_CODE_TOKEN,"token expiration")
                    }else{
                        callBack?.onError(result?.code?:Constant.ErrorCode.ERROR_CODE_UNKNOWN,result?.msg)
                    }
                }
            }
            override fun onError(code: Int, error: String?) {
                if(code == Constant.ErrorCode.ERROR_CODE_TOKEN){
                    callBack?.onError(Constant.ErrorCode.ERROR_CODE_TOKEN,"token expiration")
                }else{
                    callBack?.onError(code,error)
                }
            }
        })
    }

    inline fun <reified T>getAsync(url:String,token:String?,req:Map<String,*>?,callBack: Net.CallBack<T>?){
        val reqHeaders:HashMap<String,String> = HashMap()
//        reqHeaders["Content-Type"] = "application/json;charset=utf-8"
        if(!token.isNullOrBlank()){
            reqHeaders["Authorization"] = "Bearer ${token}"
        }
//        Log.d("token","token:${InitManager.instance.token!!}")
        NetRequest.getAsync(url, reqHeaders,req, object :Net.CallBack<ApiResult<T?>>{
            override fun onSuccess(result: ApiResult<T?>?) {
                if(result?.isResultSuccess() == true){
                    callBack?.onSuccess(result.data)
                }else{
                    if(result?.code == Constant.ErrorCode.ERROR_CODE_TOKEN){
                        callBack?.onError(Constant.ErrorCode.ERROR_CODE_TOKEN,"token expiration")
                    }else{
                        callBack?.onError(result?.code?:Constant.ErrorCode.ERROR_CODE_UNKNOWN,result?.msg)
                    }
                }
            }
            override fun onError(code: Int, error: String?) {
                if(code == Constant.ErrorCode.ERROR_CODE_TOKEN){
                    callBack?.onError(Constant.ErrorCode.ERROR_CODE_TOKEN,"token expiration")
                }else{
                    callBack?.onError(code,error)
                }

            }
        })
    }
}